package LeetCode.leetcode;

import domain.ListNode;

/**
 * 合并两个有序列表
 * @author: leiwenkang02@meituan.com
 * @date: 2018/8/7
 * @time: 21:27
 */
public class Test21合并两个有序链表 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l11 = new ListNode(2);
        ListNode l12 = new ListNode(4);
        l1.next = l11;
        l11.next = l12;

        ListNode l2 = new ListNode(1);
        ListNode l21 = new ListNode(3);
        ListNode l22 = new ListNode(4);
        l2.next = l21;
        l21.next = l22;

        ListNode newHead = mergeTwoLists(l1, l2);
        ListNode p = newHead;
        while (p != null) {
            System.out.println(p.val);
            p = p.next;
        }

    }
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode node1 = l1;
        ListNode node2 = l2;
        ListNode newNode;
        if (node1.val <= node2.val) {
            newNode = node1;
            node1 = node1.next;
        } else {
            newNode = node2;
            node2 = node2.next;
        }
        ListNode third = newNode;
        while (node1 != null && node2 != null) {
            if (node1.val <= node2.val) {
                third.next = node1;
                node1 = node1.next;

            } else {
                third.next = node2;
                node2 = node2.next;
            }
            third = third.next;
        }
        while (node1 != null) {
            third.next = node1;
            node1 = node1.next;
            third = third.next;
        }

        while (node2 != null) {
            third.next = node2;
            node2 = node2.next;
            third = third.next;
        }


        return newNode;

    }
}
